package com.gla.market.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.SpannableString;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.mikephil.charting.charts.HorizontalBarChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.gla.market.R;
import com.gla.market.adapter.FYH_CommodityAdapter;
import com.gla.market.constant.Constants;
import com.gla.market.entity.Commodity;
import com.gla.market.entity.FYH_Evaluation;
import com.gla.market.entity.FYH_Shop;
import com.gla.market.utils.NetUtil;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class Shop_FYHActivity extends AppCompatActivity {
    private boolean ispet, isnoe = false;
    private String shopid;
    private FYH_Shop thisshop;
    private TextView tvmore, tvid, tvback, pettv, usetv;
    private ImageView spphoto, petimg, useimg;

    //饼图
    private PieChart pieChart;
    //横向柱状图
    private HorizontalBarChart barHor;

    private LinearLayout petlayout, uselayout;
    private Drawable graydw, pinkdw;

    private ProgressBar commodityProgressBar;

    //下拉刷新的layout
    private SwipeRefreshLayout mRefreshLayout;
    private GridView recommendProductGridView;

    //一次请求到分页商品数据,热评商品List
    private List<Commodity> listpet = new ArrayList<>();
    private FYH_CommodityAdapter petAdapter;
    private List<Commodity> listuse = new ArrayList<>();
    private FYH_CommodityAdapter useAdapter;

    private List<FYH_Evaluation> lfe = new ArrayList<>();
    private float da[] = {0, 0, 0, 0, 0};
    private int nu[] = {0,0,0,0,0};
    private float mxy;
    private DecimalFormat df=new DecimalFormat("#.00");

    //定义一个自己的context
    private Context mContext;

    //商店信息
    private Handler uiHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case -1:
                    //网络请求失败
                    Toast.makeText(mContext, "网络请求失败！", Toast.LENGTH_SHORT).show();
                    break;
                case 0:
                    //网络请求成功，但是返回状态为失败
                    Toast.makeText(mContext, msg.obj == null ? "获取商店数据失败！" : msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    String name = thisshop.getName();
                    if(name.length() > 10) name = name.substring(0, 10) + "...";
                    tvid.setText(name);
                    if(!"".equals(thisshop.getPhoto())) {
                        ImageLoader.getInstance().displayImage(thisshop.getPhoto(), spphoto);
                    }else{
                        spphoto.setImageResource(R.drawable.fyh_shop_mr);
                    }
                    GetPet();
                    break;
                case 3:
                    makedanu();
                    // 初始化饼图
                    initPieChart();
                    //初始化柱状图
                    loadData();
                    break;
                default:
                    break;
            }
        }
    };

    //宠物信息
    private Handler petHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case -1:
                    //网络请求失败
                    Toast.makeText(mContext, "网络请求失败！", Toast.LENGTH_SHORT).show();
                    break;
                case 0:
                    //网络请求成功，但是返回状态为失败
                    Toast.makeText(mContext, msg.obj == null ? "获取商店数据失败！" : msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    petAdapter = new FYH_CommodityAdapter(mContext, listpet);
                    listpet.size();
                    recommendProductGridView.setAdapter(petAdapter);
                    //根据数量动态设置高度
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(GridView.LayoutParams.MATCH_PARENT,dip2px(mContext,(listpet.size()+1)/2 * 240));
                    recommendProductGridView.setLayoutParams(params);
                    //设置gridView点击事件
                    recommendProductGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            TextView tvid = view.findViewById(R.id.shop_id);
                            Intent intent = new Intent(Shop_FYHActivity.this, Commodity_FYHActivity.class);
                            //将对应的产品id传到详情界面
                            intent.putExtra("id", tvid.getText().toString());
                            startActivity(intent);
                        }
                    });
                    commodityProgressBar.setVisibility(View.GONE);
                    recommendProductGridView.setVisibility(View.VISIBLE);
                    break;
                default:
                    break;
            }
            //判断刷新动画
            if (mRefreshLayout.isRefreshing()) {
                //停止动画
                mRefreshLayout.setRefreshing(false);
            }
        }
    };

    //用品信息
    private Handler useHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case -1:
                    //网络请求失败
                    Toast.makeText(mContext, "网络请求失败！", Toast.LENGTH_SHORT).show();
                    break;
                case 0:
                    //网络请求成功，但是返回状态为失败
                    Toast.makeText(mContext, msg.obj == null ? "获取商店数据失败！" : msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    useAdapter = new FYH_CommodityAdapter(mContext, listuse);
                    recommendProductGridView.setAdapter(useAdapter);
                    //设置gridView点击事件
                    recommendProductGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            TextView tvid = view.findViewById(R.id.shop_id);
                            Intent intent = new Intent(Shop_FYHActivity.this, Commodity_FYHActivity.class);
                            //将对应的产品id传到详情界面
                            intent.putExtra("id", tvid.getText().toString());
                            startActivity(intent);
                        }
                    });
                    commodityProgressBar.setVisibility(View.GONE);
                    recommendProductGridView.setVisibility(View.VISIBLE);
                    break;
                default:
                    break;
            }
            //判断刷新动画
            if (mRefreshLayout.isRefreshing()) {
                //停止动画
                mRefreshLayout.setRefreshing(false);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_fyhactivity);

        //转存context
        mContext = this;

        ispet = true;

        Intent intent = getIntent();
        shopid = intent.getStringExtra("id");

        //绑定控件
        mRefreshLayout = findViewById(R.id.refresh_layout);
        commodityProgressBar = findViewById(R.id.commodity_progress);
        recommendProductGridView = findViewById(R.id.recommend_gridview);
        tvmore = findViewById(R.id.commodity_useless);
        tvid = findViewById(R.id.commodity_name);
        tvback = findViewById(R.id.commodity_back);
        spphoto = findViewById(R.id.shop_photo_in);
        petlayout = findViewById(R.id.petlayout);
        uselayout = findViewById(R.id.uselayout);
        pettv = findViewById(R.id.pettv);
        usetv = findViewById(R.id.usetv);
        petimg = findViewById(R.id.petimg);
        useimg = findViewById(R.id.useimg);
        barHor = (HorizontalBarChart) findViewById(R.id.bar_hor);
        pieChart = findViewById(R.id.pie_chart);

        graydw = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.gray_card, null);
        pinkdw = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.pink_card, null);

        petlayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commodityProgressBar.setVisibility(View.VISIBLE);
                recommendProductGridView.setVisibility(View.GONE);
                GetPet();
                ispet = true;
                useimg.setBackground(graydw);
                petimg.setBackground(pinkdw);
            }
        });

        uselayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commodityProgressBar.setVisibility(View.VISIBLE);
                recommendProductGridView.setVisibility(View.GONE);
                GetUse();
                ispet = false;
                petimg.setBackground(graydw);
                useimg.setBackground(pinkdw);
            }
        });

        tvmore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog alertDialog2 = new AlertDialog.Builder(mContext)
                        .setTitle("商店详情")
                        .setMessage("店名：" + thisshop.getName() + "\n地址：" + thisshop.getAddress() + "\n简介：" + thisshop.getIntroduction())
                        .setIcon(R.mipmap.ic_launcher)
                        .setNegativeButton("关闭", new DialogInterface.OnClickListener() {//添加取消
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {}
                        })
                        .create();
                alertDialog2.show();
            }
        });

        tvid.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(mContext, thisshop.getName(), Toast.LENGTH_SHORT).show();
            }
        });

        tvback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mRefreshLayout.setOnRefreshListener(mRefreshListener);

        GetShopMessage();
        GetEva();
        petimg.setBackground(pinkdw);
    }

    private void makedanu(){
        if(lfe.size()>0) {
            isnoe = false;
            float s = (float) lfe.size(), mx = 0;
            int x1 = 0, x2 = 0, x3 = 0, x4 = 0, x5 = 0;
            for (int i = 0; i < lfe.size(); i++) {
                switch (lfe.get(i).getPoint()) {
                    case 1:
                        x1++;
                        break;
                    case 2:
                        x2++;
                        break;
                    case 3:
                        x3++;
                        break;
                    case 4:
                        x4++;
                        break;
                    case 5:
                        x5++;
                        break;
                }
            }
            da[0] = x1 / s;
            if(da[0] > mx) mx = da[0];
            da[1] = x2 / s;
            if(da[1] > mx) mx = da[1];
            da[2] = x3 / s;
            if(da[2] > mx) mx = da[2];
            da[3] = x4 / s;
            if(da[3] > mx) mx = da[3];
            da[4] = x5 / s;
            if(da[4] > mx) mx = da[4];
            nu[0] = x1;
            nu[1] = x2;
            nu[2] = x3;
            nu[3] = x4;
            nu[4] = x5;
            mxy = (float) (mx * 1.25);
        }else {isnoe = true;}
    }

    //设置y轴
    private void setYAxis() {
        //两边的y轴都要设置y轴的最小值才能在柱状图上面显示数值
        //不然是看不到效果的
        YAxis tepAxis = barHor.getAxisLeft();
        tepAxis.setAxisMaximum(mxy);
        tepAxis.setAxisMinimum(0f);
        tepAxis.setEnabled(false);
        YAxis yAxis = barHor.getAxisRight();
        yAxis.setAxisMinimum(0f);
        yAxis.setAxisMaximum(mxy);
    }

    //设置x轴
    private void setXAxis() {
        XAxis xAxis = barHor.getXAxis();
        xAxis.setGranularity(1f);
        xAxis.setTextSize(10);
        xAxis.setAxisMaximum(4.3f);
        //把最小值设置为负数能够为下方留出点空白距离
        xAxis.setAxisMinimum(-0.3f);
        xAxis.setDrawGridLines(false);
        //将x轴显示在左侧
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        //自定义样式
        final String ss[] = {"1分", "2分", "3分", "4分", "5分"};
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return ss[(int) value];
            }
        });

    }

    //加载数据
    private void loadData() {
        setXAxis();
        setYAxis();
        barHor.setScaleXEnabled(false);
        barHor.setScaleYEnabled(false);
        barHor.setScaleEnabled(false);
        //不绘制图例
        barHor.getLegend().setEnabled(false);
        barHor.getDescription().setEnabled(false);
        barHor.getAxisRight().setEnabled(false);
        barHor.getAxisLeft().setEnabled(false);
        //自动对齐
        barHor.setFitBars(true);
        barHor.setExtraOffsets(0,5,0,5);
        //将文本绘制在柱块上还是柱块里面
        barHor.setDrawValueAboveBar(true);

        //从下往上绘制
        final List<BarEntry> entries = new ArrayList<BarEntry>();

        for(int i = 0; i < da.length; i++){
            entries.add(new BarEntry(i,da[i]));
        }

        BarDataSet barDataSet = new BarDataSet(entries,"");
        barDataSet.setValueTextSize(10f);//柱块上的字体大小
        barDataSet.setValueTextColor(Color.RED);//柱块上的字体颜色
        //自自定义样式
        barDataSet.setValueFormatter(new IValueFormatter() {
            @Override
            public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                return nu[(int)entry.getX()] + "";//保留两位小数
            }
        });
        //依次设置每次柱块的颜色
        barDataSet.setColors(getResources().getColor(R.color.hhn_pink));
        BarData barData = new BarData(barDataSet);
        //设置柱块的宽度
        barData.setBarWidth(0.6f);
        barHor.setData(barData);
        barHor.notifyDataSetChanged();
        barHor.invalidate();
    }

    private void initPieChart() {
        pieChart.getDescription().setEnabled(false); // 不显示描述
        pieChart.setDrawHoleEnabled(true); // 不显示饼图中间的空洞
        SpannableString s;
        if(isnoe){
            s = new SpannableString("暂无评价");
        }else {
            s = new SpannableString("好评率\n" + (int)((da[4] + da[3] + da[2]) * 100) + "%");
        }
        pieChart.setCenterText(s);
        pieChart.setExtraOffsets(5, 5, 5, 5); // 设置饼图的偏移量，类似于内边距 ，设置视图窗口大小
        setLegend(); // 设置图例
        setData(); // 为饼图设置数据
    }

    private void setData() {
        List<PieEntry> pieEntries = new ArrayList<>();
        // 准备饼图中要显示的数据
        if(isnoe){
            pieEntries.add(new PieEntry(100, "暂无评价"));
        }else {
            if(da[0] > 0) pieEntries.add(new PieEntry(Float.parseFloat(df.format(da[0])), "1分"));
            if(da[1] > 0) pieEntries.add(new PieEntry(Float.parseFloat(df.format(da[1])), "2分"));
            if(da[2] > 0) pieEntries.add(new PieEntry(Float.parseFloat(df.format(da[2])), "3分"));
            if(da[3] > 0) pieEntries.add(new PieEntry(Float.parseFloat(df.format(da[3])), "4分"));
            if(da[4] > 0) pieEntries.add(new PieEntry(Float.parseFloat(df.format(da[4])), "5分"));
        }
        // 把准备好的数据统一进行格式设置
        PieDataSet pieDataSet = new PieDataSet(pieEntries, "");
        // 设置饼图各部分的颜色
        pieDataSet.setColors(getResources().getColor(R.color.hhn_pink));
        // 设置饼图中数据显示的格式
        pieDataSet.setValueFormatter(new IValueFormatter() {
            @Override
            public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                return value + "%";
            }
        });
        pieDataSet.setValueTextSize(10f);
        pieDataSet.setSliceSpace(5f); // 设置扇区中的间隔
        // 设置饼图显示的线
        pieDataSet.setValueLineColor(Color.BLACK);
        pieDataSet.setYValuePosition(PieDataSet.ValuePosition.INSIDE_SLICE); // 设置值显示的位置

        PieData pieData = new PieData(pieDataSet);
        pieChart.setData(pieData); // 为饼图设置数据
        pieChart.notifyDataSetChanged();
        pieChart.invalidate();
    }

    private void setLegend() {
        Legend legend = pieChart.getLegend();
        legend.setEnabled(false);
    }

    //刷新
    private SwipeRefreshLayout.OnRefreshListener mRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            if(ispet) GetPet();
            else GetUse();
        }
    };

    //获取用品
    private void GetUse() {
        String url = Constants.BASE_URL + Constants.GET_FYH_SHOP_URL + Constants.GET_FYH_CMBYSIDPOU_URL + Constants.cmbysidpouIn(thisshop.getId(), 1);
        NetUtil.doGet(url, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("调试", "错误信息：" + e.toString());
                        Message message = Message.obtain();
                        message.what = -1;
                        uiHandler.sendMessage(message);
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string().trim();
                        com.alibaba.fastjson.JSONObject object = JSON.parseObject(result);
                        Message message = Message.obtain();
                        if (!object.getString("message").contains("JWT") && object.getString("error")==null && object.getInteger("code")==100) {
                            JSONArray array = object.getJSONArray("data");
                            //获得商品list
                            listuse = JSONArray.parseArray(array.toString(), Commodity.class);
                            message.what = 2;
                        } else {
                            message.what = 0;
                        }
                        useHandler.sendMessage(message);
                    }
                }
        );
    }

    //获取宠物
    private void GetPet() {
        String url = Constants.BASE_URL + Constants.GET_FYH_SHOP_URL + Constants.GET_FYH_CMBYSIDPOU_URL + Constants.cmbysidpouIn(thisshop.getId(), 0);
        NetUtil.doGet(url, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("调试", "错误信息：" + e.toString());
                        Message message = Message.obtain();
                        message.what = -1;
                        uiHandler.sendMessage(message);
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string().trim();
                        com.alibaba.fastjson.JSONObject object = JSON.parseObject(result);
                        Message message = Message.obtain();
                        if (!object.getString("message").contains("JWT") && object.getString("error")==null && object.getInteger("code")==100) {
                            JSONArray array = object.getJSONArray("data");
                            //获得商品list
                            listpet = JSONArray.parseArray(array.toString(), Commodity.class);
                            message.what = 2;
                        } else {
                            message.what = 0;
                        }
                        petHandler.sendMessage(message);
                    }
                }
        );
    }

    //获取商店
    private void GetShopMessage() {
        String url = Constants.BASE_URL + Constants.GET_FYH_SHOP_URL + Constants.GET_FYH_ONESHOP_URL + shopid;
        NetUtil.doGet(url, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("调试", "错误信息：" + e.toString());
                        Message message = Message.obtain();
                        message.what = -1;
                        uiHandler.sendMessage(message);
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string().trim();
                        com.alibaba.fastjson.JSONObject object = JSON.parseObject(result);
                        Message message = Message.obtain();
                        if (!object.getString("message").contains("JWT") && object.getString("error")==null && object.getInteger("code")==100) {
                            JSONObject jshop = object.getJSONObject("data");
                            //获得商品list
                            thisshop = JSONObject.parseObject(String.valueOf(jshop), FYH_Shop.class);
                            message.what = 2;
                        } else {
                            message.what = 0;
                        }
                        uiHandler.sendMessage(message);
                    }
                }
        );
    }

    //获取评论
    private void GetEva() {
        String url = Constants.BASE_URL + Constants.GET_FYH_SHOP_URL + Constants.GET_FYH_EVABYSPID_URL + shopid;
        NetUtil.doGet(url, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("调试", "错误信息：" + e.toString());
                        Message message = Message.obtain();
                        message.what = -1;
                        uiHandler.sendMessage(message);
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string().trim();
                        com.alibaba.fastjson.JSONObject object = JSON.parseObject(result);
                        Message message = Message.obtain();
                        if (object!=null && object.getInteger("code")==100) {
                            JSONArray array = object.getJSONArray("data");
                            //获得商品list
                            lfe = JSONArray.parseArray(array.toString(), FYH_Evaluation.class);
                            message.what = 3;
                        } else {
                            message.what = 0;
                        }
                        uiHandler.sendMessage(message);
                    }
                }
        );
    }
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}